package com.tokenplus.thai.aviewmodel

import android.content.res.Resources
import android.util.DisplayMetrics
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.tokenplus.thai.ProjectApplication
import com.tokenplus.thai.adata.checkin.RevDataGetCheckinDetail
import com.tokenplus.thai.anetwork.ApiUserReposity
import com.tokenplus.thai.base.BaseViewModel
import com.tokenplus.thai.checkin.adapter.CheckinDay
import com.tokenplus.thai.data.ReqBase
import com.tokenplus.thai.extend.dpToPx
import com.tokenplus.thai.utils.CalendarUtil
import com.tokenplus.thai.utils.SpUtil


class CheckinViewModel : BaseViewModel() {

    val _monthDes = mutableListOf(
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    )

    var mCurMonth: String = ""

    val mWeekList = mutableListOf<CheckinDay>().apply {
        // 每个item的宽高
        val resources: Resources = ProjectApplication.instance.resources
        val metrics: DisplayMetrics = resources.displayMetrics
        val screenWidth = metrics.widthPixels
        var itemSize = (screenWidth - ((12 + 12) * 2).dpToPx(ProjectApplication.instance)) / 7
        itemSize -= (24.dpToPx(ProjectApplication.instance))

        add(
            CheckinDay(
                day = "Mo",
                isCurrentMonth = false,
                isCurrentDay = false,
                isCheckIn = false,
                week = "0",
                size = itemSize
            )
        )
        add(
            CheckinDay(
                day = "Tu",
                isCurrentMonth = false,
                isCurrentDay = false,
                isCheckIn = false,
                week = "1",
                size = itemSize
            )
        )
        add(
            CheckinDay(
                day = "We",
                isCurrentMonth = false,
                isCurrentDay = false,
                isCheckIn = false,
                week = "2",
                size = itemSize
            )
        )
        add(
            CheckinDay(
                day = "Th",
                isCurrentMonth = false,
                isCurrentDay = false,
                isCheckIn = false,
                week = "3",
                size = itemSize
            )
        )
        add(
            CheckinDay(
                day = "Fr",
                isCurrentMonth = false,
                isCurrentDay = false,
                isCheckIn = false,
                week = "4",
                size = itemSize
            )
        )
        add(
            CheckinDay(
                day = "Sa",
                isCurrentMonth = false,
                isCurrentDay = false,
                isCheckIn = false,
                week = "5",
                size = itemSize
            )
        )
        add(
            CheckinDay(
                day = "Su",
                isCurrentMonth = false,
                isCurrentDay = false,
                isCheckIn = false,
                week = "6",
                size = itemSize
            )
        )
    }
    val mDayList = mutableListOf<CheckinDay>()

    //////////////////////////////////////////
    private val mGetCheckinDetailLiveData = MutableLiveData<ReqBase>()

    val onGetCheckinDetailLiveData =
        Transformations.switchMap(mGetCheckinDetailLiveData) { query ->
            ApiUserReposity.getCheckinDetail(this, query)
        }

    fun getCheckinDetail(reqBase: ReqBase) {
        mGetCheckinDetailLiveData.value = reqBase
    }

    //////////////////////////////////////////
    private val mCheckinLiveData = MutableLiveData<ReqBase>()

    val onCheckinLiveData =
        Transformations.switchMap(mCheckinLiveData) { query ->
            ApiUserReposity.checkin(this, query)
        }

    fun checkin(reqBase: ReqBase) {
        mCheckinLiveData.value = reqBase
    }

    //////////////////////////////////////////
    val onTodayDidCheckinLiveData = MutableLiveData<Boolean>()
    var mCheckinDayIncome: String = ""

    fun showCurDayCheckinSuccess() {
        for (i in 0 until mDayList.size) {
            val data = mDayList[i]
            if (data.isCurrentDay) {
                data.showSuccess = true
                break
            } else {
                data.showSuccess = false
            }
        }
    }

    fun curDayItemPosition(): Int {
        for (i in 0 until mDayList.size) {
            val data = mDayList[i]
            if (data.isCurrentDay) {
                return i
            }
        }
        return 0
    }

    fun updateCheckinDetail(
        revDataGetCheckinDetail: RevDataGetCheckinDetail?
    ) {
        mDayList.clear()

        // 每次签到的收益
        if (revDataGetCheckinDetail != null) {
            mCheckinDayIncome = revDataGetCheckinDetail.dayIncome ?: ""
        }

        // 每个item的宽高
        val resources: Resources = ProjectApplication.instance.resources
        val metrics: DisplayMetrics = resources.displayMetrics
        val screenWidth = metrics.widthPixels
        var itemSize = (screenWidth - ((12 + 12) * 2).dpToPx(ProjectApplication.instance)) / 7
        itemSize -= (24.dpToPx(ProjectApplication.instance))

        val curMonthInfo = CalendarUtil.getCurMonthInfo()
        curMonthInfo.printLog()

        // 更新月份
        mCurMonth = _monthDes[curMonthInfo.month - 1]

        // 需要显示上个月的天数
//        val needPrefixDays = curMonthInfo.firstDayWeek.toInt() - 1
        val needPrefixDays = curMonthInfo.firstDayWeek.toInt()
        if (needPrefixDays > 0) {
            // 获取上个月的天数
            var perYear = curMonthInfo.year
            var preMonth = curMonthInfo.month - 1
            if (preMonth <= 0) {
                preMonth = 12
                perYear -= 1
            }
            val preMonthDays = CalendarUtil.getDaysInMonth(perYear, preMonth)

            // 如差3天
            for (i in 0 until needPrefixDays) {
                val day = (preMonthDays - needPrefixDays + 1 + i);
                mDayList.add(
                    CheckinDay(
                        day = day.toString(),
                        isCurrentMonth = false,
                        isCurrentDay = false,
                        isCheckIn = false,
                        week = (i + 1).toString(),
                        size = itemSize
                    )
                )
            }
        }

        // 当月
        val curMonth = curMonthInfo.month
        val curMonthFormat = if (curMonth < 10) {
            "0$curMonth"
        } else {
            "$curMonth"
        }

        val curMonthYear = curMonthInfo.year
        val curMonthDay = curMonthInfo.curDay
        val curMonthDayFormat = if (curMonthDay.length < 2) {
            "0$curMonthDay"
        } else {
            curMonthDay
        }

        val curMonthDays = curMonthInfo.days
        println("curMonthDays: $curMonthDays")
        for (i in 0 until curMonthDays) {
            // 判断是否为当天
            var isCurrentDay = false
            val day = (i + 1).toString()
            if (day == curMonthDay) {
                isCurrentDay = true
            }

            // 判断是否为已签到
            val dayFormat = if (day.length < 2) {
                "0$day"
            } else {
                day
            }
            val fullDay = "$curMonthYear-$curMonthFormat-$dayFormat"
            var isCheckIn = false
            if (revDataGetCheckinDetail != null) {
                if (revDataGetCheckinDetail.signinDays != null) {
                    for (sDay in revDataGetCheckinDetail.signinDays) {
                        if (sDay == fullDay) {
                            isCheckIn = true
                            break
                        }
                    }
                }
            }

            // 查每天星期
            val week = CalendarUtil.getDayOfWeek(curMonthYear, curMonth, curMonthDay.toInt())
            mDayList.add(
                CheckinDay(
                    day = day,
                    isCurrentMonth = true,
                    isCurrentDay = isCurrentDay,
                    isCheckIn = isCheckIn,
                    week = week.toString(),
                    size = itemSize
                )
            )
        }

        // 当月最后天是星期几
        val lastDayWeek = CalendarUtil.getDayOfWeek(curMonthYear, curMonth, curMonthDays)
        println("lastDayWeek:$lastDayWeek")
        val needLastDays = 7 - lastDayWeek
        if (needLastDays > 0) {
            for (i in 0 until needLastDays) {
                mDayList.add(
                    CheckinDay(
                        day = (i + 1).toString(),
                        isCurrentMonth = false,
                        isCurrentDay = false,
                        isCheckIn = false,
                        week = (lastDayWeek + 1 + i).toString(),
                        size = itemSize
                    )
                )
            }
        }

        // 判断当天是否已签到
        val fullDay = "$curMonthYear-$curMonthFormat-$curMonthDayFormat"
        var todayDidCheckin = false
        if (revDataGetCheckinDetail != null) {
            if (revDataGetCheckinDetail.signinDays != null) {
                todayDidCheckin = revDataGetCheckinDetail.signinDays.any {
                    it == fullDay
                }
            }
        }
        onTodayDidCheckinLiveData.value = todayDidCheckin

    }


    //////////////////////////////////////////
    private val mGetRedMarkInfoLiveData = MutableLiveData<ReqBase>()

    val onGetRedMarkInfoLiveData =
        Transformations.switchMap(mGetRedMarkInfoLiveData) { query ->
            ApiUserReposity.getRedMarkInfo(this, query)
        }

    fun getRedMarkInfo(reqBase: ReqBase) {
        mGetRedMarkInfoLiveData.value = reqBase
    }

    fun needShowCheckinRemindDialog(): Boolean {
        val curMonthInfo = CalendarUtil.getCurMonthInfo()
        val year = curMonthInfo.year
        val month = curMonthInfo.month
        val day = curMonthInfo.curDay
        val key = "$year-$month-$day"

        val domain = "CHECK_REMIND_TODAY"
        val cached = SpUtil.getStringValue(domain)

        return key != cached
    }

    fun todayDidShowCheckinRemindDialog() {
        val curMonthInfo = CalendarUtil.getCurMonthInfo()
        val year = curMonthInfo.year
        val month = curMonthInfo.month
        val day = curMonthInfo.curDay
        val key = "$year-$month-$day"

        val domain = "CHECK_REMIND_TODAY"
        SpUtil.saveSpValue(domain, key)
    }
}